/**
 * Created by yangxianming on 2020/12/30.
 */
//
//接口定义 都是以api开头 所需参数都通过方法传入
//function apiGetCorpList(dofun, envText){}
//

var beforeWords1 = "";   //记录修改前的文字，为了和失去光标后的输入内容做对比，以判断是否要保存
var beforeWords2 = "";   //记录修改前的文字，为了和失去光标后的输入内容做对比，以判断是否要保存
var beforeWords3 = "";   //记录修改前的文字，为了和失去光标后的输入内容做对比，以判断是否要保存
var newCount = 0;       //区别连续页面新建用例的id

//获得case列表
function showCase(){
    var version = selectedText(document.getElementById("version"));
    var value = "action=showCase&progressName="+version;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/progressCase/showProgressCase?" + value, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    //console.log(r["result"]);
                    addModuleWithData(r["result"]);
                    getModule(version);
                }
                if (r["apiStatus"] == "0"){
                    alert(r["errorMsg"]);
                }
            }
        }
    };
    xmlHttp.send();
}

//更新用例状态
function updateCase(caseObj, state){
    var uuid = caseObj.getElementsByTagName("div")[1].getAttribute("id");

    var saveData = {"action": "update"};
    saveData["data"] = {
        "uuid":uuid,
        "state": state
    };

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/progressCase/saveProgressCase", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    //console.log(r)
                }
                if (r["apiStatus"] == "0"){
                    alert(r["errorMsg"]);
                }
            }
        }
    };

    xmlHttp.send(JSON.stringify(saveData));
}

//添加用例
function addCase(caseObj){
    //caseObj 是每条用例最外层的div
    //('regfgfd234343', '口福3.4', '首页', '这个是标题', '这个是前置条件', '这个操作步骤', '1')
    var title = caseObj.getElementsByTagName("div")[0].getElementsByTagName("input")[0].value;
    var condition = caseObj.getElementsByTagName("div")[1].getElementsByTagName("div")[0].getElementsByTagName("textarea")[0].value;
    var steps = caseObj.getElementsByTagName("div")[1].getElementsByTagName("div")[1].getElementsByTagName("textarea")[0].value;
    //根据文字内容判断是否要保存
    if(title == beforeWords1 && condition == beforeWords2 && steps == beforeWords3){
        beforeWords1 = "";
        beforeWords2 = "";
        beforeWords3 = "";
        return;
    }

    var uuid = caseObj.getElementsByTagName("div")[1].getAttribute("id");
    var version = selectedText(document.getElementById("version"));
    var module = caseObj.parentNode.previousSibling.getElementsByTagName("span")[0].innerText;
    var state = caseObj.getElementsByTagName("button")[2].getAttribute("name");

    var saveData = {"action": "addCase"};
    saveData["data"] = {
        "uuid":uuid,
        "addCase": "addCase",
        "progressname": version,
        "title": title,
        "module": module,
        "condition": condition,
        "steps": steps,
        "state": state
    };

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/progressCase/saveProgressCase", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    //console.log(r);
                    var uid = r["result"];
                    //更新caseid
                    if(uid != undefined){
                        caseObj.getElementsByTagName("button")[0].setAttribute("data-target", "#"+uid);
                        caseObj.getElementsByTagName("div")[1].setAttribute("id", uid);
                    }
                }
                if (r["apiStatus"] == "0"){
                    alert(r["errorMsg"]);
                }
            }
        }
    };

    xmlHttp.send(JSON.stringify(saveData));
}

//获得版本列表
function getVersion(selectVersion){
    var year = document.getElementById("year").value;
    var project = selectedText(document.getElementById("project"));
    var value = "action=getVersion&year="+year+"&project="+project;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/progressCase/getVersion?" + value, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    loadSelectList(document.getElementById("version"), r["result"]);
                    if(selectVersion != "undefined"){
                        setSelectChecked(document.getElementById("version"), selectVersion);
                        showCase();
                    }
                }
                if (r["apiStatus"] == "0"){
                    alert(r["errorMsg"]);
                }
            }
        }
    };
    xmlHttp.send();
}

//获得模块列表
function getModule(project){
    //var project = selectedText(document.getElementById("project"));
    var value = "action=getModule&project="+project;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/progressCase/getModule?" + value, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    loadSelectList(document.getElementById("chooseModule"), r["result"]);
                }
                if (r["apiStatus"] == "0"){
                    alert(r["errorMsg"]);
                }
            }
        }
    };
    xmlHttp.send();
}


//
//页面渲染 都是以draw开头
//function drawGetCorpList(data){}
//

//绘制一个模块
function drawOneModula(moduleName, number, caseListData){
    //caseListData 数据格式是 caseList对象
    //[ ["moduleName":"福员外首页","caseList":[["title","condition","steps","state"],["title","condition","steps","state"]]],
    //  ["moduleName":"福员外首页2","caseList":["title","condition","steps","state"]]
    //最外层div
    var div = document.createElement("div");
    div.setAttribute("style", "display: flex;align-items: center;justify-content: flex-end; width: 100%;");
    if((number % 2) == 1){
        //#f7f7f7
        div.style.backgroundColor = "#f7f7f7";
    }else{
        //#e8e8e8
        div.style.backgroundColor = "#e8e8e8";
    }

    //模块div，内部span
    var div1 = document.createElement("div");
    div1.setAttribute("style", "width:8%; font-size: large; text-align: center");
    div.appendChild(div1);
    var span = document.createElement("span");
    span.innerText = moduleName;
    div1.appendChild(span);
    //用例条列表外层div
    var div2 = document.createElement("div");
    div2.setAttribute("style", "width:90%; flex: 1;");
    div.appendChild(div2);
    //绘制内部数据
    for(var i=0; i<caseListData.length; i++){
        var title = caseListData[i][0];
        var condition = caseListData[i][1];
        var steps = caseListData[i][2];
        var state = caseListData[i][3];
        var uuid = caseListData[i][4];
        div2.appendChild(drawOneCase(title, condition, steps, state, uuid))
    }
    //最后一个加号
    var divAdd = document.createElement("div");
    var button = document.createElement("button");
    button.setAttribute("style", "width: 70px; border: 0; font-size: large");
    button.onclick = function(){drawOneCaseNull(this)};
    button.innerText = "+";
    divAdd.appendChild(button);
    div2.appendChild(divAdd);

    return div;
}

//添加一条空用例
function drawOneCaseNull(obj){
    var b = obj.parentNode;
    var myL = obj.parentNode.parentNode;
    var lengt = obj.parentNode.parentNode.childNodes;
    myL.removeChild(lengt[lengt.length-1]);
    myL.appendChild(drawOneCase("","","","1","new"+newCount++));
    myL.appendChild(b);
}

//绘制一条用例
function drawOneCase(title, condition, steps, state, number){
    //4个是用例数据title, condition, steps, state
    //这个是序号number，如果是有参数
    //最外层div
    var div1 = document.createElement("div");
    div1.style.width = "100%";
    //详细下拉按钮
    var button1 = document.createElement("button");
    button1.className = "progresscase";
    button1.setAttribute("style", "float:left;");
    button1.setAttribute("data-toggle", "collapse");
    button1.setAttribute("data-target", "#" + number);
    button1.setAttribute("title", "下拉编辑详情");
    button1.setAttribute("aria-expanded", "true");
    button1.innerText = "详细";
    div1.appendChild(button1);
    //复制按钮
    var button2 = document.createElement("button");
    button2.className = "progresscase";
    button2.setAttribute("title", "复制");
    button2.innerText = "复制";
    div1.appendChild(button2);
    //状态按钮  初始 与 运行 红 ffcfce  绿 d0ffc2
    var button3 = document.createElement("button");
    button3.className = "progresscase";
    button3.title = "状态";
    if(state == "1"){
        button3.name = "1";
        button3.innerText = "初始";
    }
    if(state == "2"){
        button3.style.background = "#d0ffc2";
        button3.name = "2";
        button3.innerText = "执行";
    }
    if(state == "3"){
        button3.style.background = "#ffcfce";
        button3.name = "3";
        button3.innerText = "废弃";
    }
    button3.onclick = function(){drawUpdateState(this)};
    div1.appendChild(button3);

    //标题div和内部的input
    var div2 = document.createElement("div");
    div2.style.width = "850px";
    div1.appendChild(div2);
    //input
    var input1 = document.createElement("input");
    input1.setAttribute("style", "width: 100%; border: 0;background-color: inherit");
    input1.type = "text";
    input1.placeholder = "这里是标题";
    input1.style.fontSize = "17px";
    input1.value = title;
    input1.onclick = function(){beforeWords1 = input1.value;beforeWords2 = textarea1.value;beforeWords3 = textarea2.value};
    input1.onblur = function(){addCase(this.parentNode.parentNode, beforeWords1)};
    div2.appendChild(input1);

    //详细内容div和内部的2个div，textarea
    var div3 = document.createElement("div");
    div3.style.width = "100%";
    div3.id = number;
    div3.className = "collapse";
    div1.appendChild(div3);

    var div4 = document.createElement("div");
    div4.style.width = "100%";
    div3.appendChild(div4);
    var textarea1 = document.createElement("textarea");
    textarea1.style.width = "100%";
    textarea1.placeholder = "预置条件";
    textarea1.value = condition;
    textarea1.onclick = function(){beforeWords1 = input1.value;beforeWords2 = textarea1.value;beforeWords3 = textarea2.value};
    textarea1.onblur = function(){addCase(this.parentNode.parentNode.parentNode, beforeWords2)};
    div4.appendChild(textarea1);

    var div5 = document.createElement("div");
    div5.style.width = "100%";
    div3.appendChild(div5);
    var textarea2 = document.createElement("textarea");
    textarea2.setAttribute("style", "width: 100%; min-height: 150px");
    textarea2.placeholder = "预置条件";
    textarea2.value = steps;
    textarea2.onclick = function(){beforeWords1 = input1.value;beforeWords2 = textarea1.value;beforeWords3 = textarea2.value};
    textarea2.onblur = function(){addCase(this.parentNode.parentNode.parentNode, beforeWords3)};
    div5.appendChild(textarea2);

    return div1;
}

//预览进度表  红 ffcfce  绿 d0ffc2
function drawUpdateState(obj){
    var state = obj;
    if(state.getAttribute("name") == "1"){
        state.setAttribute("name", "2");
        state.style.background = "#d0ffc2";
        state.innerText = "执行";
        updateCase(obj.parentNode, "2");
        return;
    }
    if(state.getAttribute("name") == "2"){
        state.setAttribute("name", "3");
        state.style.background = "#ffcfce";
        state.innerText = "废弃";
        updateCase(obj.parentNode, "3");
        return;
    }
    if(state.getAttribute("name") == "3"){
        state.setAttribute("name", "1");
        state.style.background = "";
        state.innerText = "初始";
        updateCase(obj.parentNode, "1");
    }
}


//
//页面调用 数据获取，接口层与渲染层的连接
//


function initializeData(){
    //通过url拿到项目参数
    var pro = decodeURI(getQueryVariable("project"));

    //查询历史档案页面 填充当前年份
    var da = new Date();
    document.getElementById("year").value = da.getFullYear();

    //查询历史档案页面 填充项目下拉
    var progressList = ["", "福员外", "口福"];
    loadSelectList(document.getElementById("project"), progressList);

    //加载迭代版本
    getVersion(pro);

    //加载模块; 加载迭代版本成功后调用getModule()

}

//下方添加一个模块
function addModuleNullData(){
    var moduleName = selectedText(document.getElementById("chooseModule"));
    if(moduleName == ""){
        return;
    }

    var moduleDiv = document.getElementById("chooseModule").parentNode;
    var myContent = document.getElementsByClassName("content")[0];
    var moduleList = document.getElementsByClassName("content")[0].childNodes;
    var number = moduleList.length;
    myContent.removeChild(moduleList[number-1]);
    myContent.appendChild(drawOneModula(moduleName, number, []));
    myContent.appendChild(moduleDiv);
}

//选择版本轮询增加模块
function addModuleWithData(caseListData){
    //caseListData 数据格式是 caseList对象
    //测试数据 4 5 6 7 1
    //var caseListData = [
    //    {"moduleName":"福员外首页","caseList":[["可用范围选择条目，当已经选择了\"自定义区域\" 或 \"自定义品牌门店\"，再切换选择的时候会清楚之前的选择，并给出提示","condition1","steps1","1","1"],["可用范围区域限制后管信息输入验证：可以按照省市区选择限制范围，可以按照自定义范围选择限制范围","condition2","steps2","2","2"],["菜单布局\"宫格型\"，编辑菜单验证，验证内容：新增菜单，删除菜单，icon图片上传，各输入框文字输入","condition3","steps3","3","3"]]},
    //    {"moduleName":"福员外首页2","caseList":[["title4","condition4","steps2","1","4"],["title5","condition5","steps5","2","5"]]},
    //    {"moduleName":"福员外首页3","caseList":[["title6","condition6","steps6","1","6"]]}
    //];
    var choseDiv = document.getElementById("chooseModule").parentNode;
    var content = document.getElementsByClassName("content")[0];
    content.innerText = "";
    for(var i=1; i<=caseListData.length; i++){
        var moduleName = caseListData[i-1]["moduleName"];
        var list = caseListData[i-1]["caseList"];
        content.appendChild(drawOneModula(moduleName, i, list));
    }
    content.appendChild(choseDiv);
}